<?php

namespace App\Service\Admin;

use App\Model\Admin\FaceModel;
use App\Model\Admin\PersonFaceModel;
use App\Model\Admin\StudentModel;
use App\Model\Admin\StudentParentModel;
use App\Model\Admin\StudentParentRelModel;
use App\Service\BaseService;

/**
 * 学生管理-服务类
 * @author LZH
 * @since: 2021/08/12
 * Class StudentService
 */
class StudentService extends BaseService
{
    /**
     * 构造函数
     * LevelService constructor.
     */
    public function __construct()
    {
        $this->model = new StudentModel();
        parent::__construct();
    }

    /**
     * 获取数据列表
     * @return array
     * @since 2021/08/12
     * @author LZH
     */
    public function getList()
    {
        $param = $this->getRequestParam();

        // 查询条件
        $map = [];

        // 人脸检测 TODO

        // 所属班级和学部，通过 class_id 、grade_id 来获取班级和年级信息；考勤卡号，连接所有考勤卡号；关联监护人
        $result = $this->model->join('sc_classes', 'sc_classes.id = sc_student.class_id')
            ->join('sc_grade', 'sc_grade.id = sc_classes.grade_id')
            ->join('sc_student_parent_rel', 'sc_student.id = sc_student_parent_rel.student_id')
            ->join('sc_student_parent', 'sc_student_parent.id = sc_student_parent_rel.parent_id')
            ->join('sc_person_face', 'sc_person_face.user_id = sc_student.id')
            ->field(['sc_student.*', 'sc_classes.name as class_name', 'sc_grade.dept_name', "concat_ws(',', sc_student.ic_card1, sc_student.ic_card2, sc_student.ic_card3) as ic_card", "group_concat(sc_student_parent.name , concat('(',sc_student_parent.mobile, ')')) as parents", 'sc_person_face.origin_face_url as avatar'])
            ->where('sc_student.mark', 1)
            ->where('sc_student.school_code', $this->admin['school_code'])
            ->where('sc_person_face.photo_origin', 1) // 教职工上传
            ->where($map)
            ->group('sc_student.id')
            ->all()
            ->toArray(true, false);

//        //获取数据总数
//        $count = count($result);
//
//        //返回结果
//        $message = array(
//            "data" => $result,
//            "count" => $count,
//        );
        return $result;
    }

    /**
     * 新增或修改
     * @author LZH
     */
    public function edit()
    {
        $studentInfo = $this->getRequestParam();
        $temp = explode(':', $studentInfo['study_status']);
        $studentInfo['study_status_code'] = $temp[0];
        $studentInfo['study_status_name'] = $temp[1];
        $temp = explode(':', $studentInfo['idcard_type']);
        $studentInfo['idcard_type_code'] = $temp[0];
        $studentInfo['idcard_type_name'] = $temp[1];
        $temp = explode(':', $studentInfo['accommodation_type']);
        $studentInfo['accommodation_type_code'] = $temp[0];
        $studentInfo['accommodation_type_name'] = $temp[1];
        $studentInfo['school_code'] = $this->admin['school_code'];

        $studentId = parent::edit($studentInfo);

        // 支持多张照片上传
        $studentPhotos = [];
        if (strpos($studentInfo['avatar'], "temp")) { // 对于保存用户，需要把图片从临时文件转储到正式文件目录
            $studentPhotos['origin_face_url'] = save_image($studentInfo['avatar'], 'student');
        } else { // 对于编辑用户，需要把图片路径中域名部门去掉
            $studentPhotos['origin_face_url'] = str_replace(IMG_URL, "", $studentInfo['avatar']);
        }
        $studentPhotos['user_id'] = $studentId;
        $studentPhotos['photo_origin'] = 1; // 图片来自教职工上传

        // 插入sc_face人脸下发表中
        $faceData = [];
        $faceData['school_code'] = $this->admin['school_code'];
        $faceData['face_group_id'] = 1; // 平台默认初始化学生库分组
        $faceData['person_name'] = $studentInfo['name'];
        $faceData['gender'] = $studentInfo['gender'];
        $faceData['idcard_type_code'] = $studentInfo['idcard_type_code'];
        $faceData['idcard_type_name'] = $studentInfo['idcard_type_name'];
        $faceData['idcard'] = $studentInfo['idcard'];
        $faceData['birthday'] = $studentInfo['birthday'];
        $faceData['census_register'] = $studentInfo['census_register'];
        $faceData['address'] = $studentInfo['address'];
        $faceModel = new FaceModel();
        $faceId = $faceModel->edit($faceData);

        // 插入下发图片记录
        if (is_numeric($faceId)) {
            $studentPhotos['face_id'] = $faceId;
            $studentPhotos['school_code'] = $this->admin['school_code'];
            $personFaceModel = new PersonFaceModel();
            $personFaceModel->edit($studentPhotos);
        } else {
            return false; // 插入失败
        }

        // 插入学生与监护人之间关系
        $dynamicItem = $this->getRequestParam('dynamicItem'); // 保存到sc_student_parent_rel表中

        $parentsRelations = []; // 保存亲属和学生关系的信息
        foreach ($dynamicItem as &$item) {

            // 保存亲属的信息
            $studentParentModel = new StudentParentModel();
            $parentId = $studentParentModel->data([
                'name' => $item['parentName'],
                'mobile' => $item['mobile'],
                'school_code' => $this->admin['school_code'],
            ])->save();

            if (is_numeric($parentId)) {
                $temp = explode(':', $item['kindship']);
                $parentsRelations[] = [
                    'student_id' => $studentId,
                    'parent_id' => $parentId,
                    'kinship_code' => $temp[0],
                    'kinship_name' => $temp[1],
                    'school_code' => $this->admin['school_code']
                ];
            } else {
                return false; // 插入失败
            }
        }

        $studentParentRelModel = new StudentParentRelModel();
        $result = $studentParentRelModel->saveAll($parentsRelations);
        return array_keys($result);
    }
}
